<template>
    <div class="trant">
        <!-- 左边表格数据 -->
        <div class="trant-left">
            <p>未选中</p>
            <div class="trant-content" v-loading="loading">
                <div class="content-input">
                    <el-input
                        :placeholder="leftPlaceholder"
                        v-model="searchData.left.temp"
                        style="width:280px"
                        size="mini"
                        @keyup.enter.native="onSearch('left')"
                    ></el-input>
                    <el-button class="left-p" type="primary" icon="el-icon-search" @click="onSearch('left')"> </el-button>
                </div>
                <div>
                    <el-table
                        ref="leftTable"
                        :data="leftTableDataStorage"
                        tooltip-effect="dark"
                        style="width: 100%"
                        height="300px"
                        :row-key="indexKey"
                        @select="handleLeftSelections"
                        @select-all="handleLeftSelections"
                        border
                    >
                        <el-table-column type="selection" width="40" align="center" :reserve-selection="true"></el-table-column>
                        <template v-for="col in columns">
                            <el-table-column
                                v-if="!col.fun"
                                :key="col.prop"
                                :prop="col.prop"
                                :label="col.label"
                                :width="col.width"
                                show-overflow-tooltip
                            ></el-table-column>
                            <el-table-column v-if="col.fun" :key="col.prop" :label="col.label" :width="col.width" show-overflow-tooltip>
                                <template slot-scope="scope">
                                    {{ col.fun(scope.row) }}
                                </template>
                            </el-table-column>
                        </template>
                    </el-table>
                </div>
                <el-pagination
                    layout="total, prev, pager, next"
                    :total="page.left.total"
                    :page-size="page.left.pageSize"
                    :current-page="page.left.currentPage"
                    @current-change="changeLeftCurrentPage"
                    background
                ></el-pagination>
            </div>
        </div>

        <!-- 中间2个键 -->
        <div class="trant-but">
            <!--  <el-button-->
            <!--      type="primary"-->
            <!--      icon="el-icon-d-arrow-right"-->
            <!--      :disabled="!leftTableDataStorage.length"-->
            <!--      @click="moveAllSelections('left', 'right')"-->
            <!--  ></el-button>-->
            <!--  <br /> -->
            <el-button
                type="primary"
                icon="el-icon-arrow-right"
                :disabled="!leftTableDataStorage.length"
                @click="moveSelections('left', 'right')"
            ></el-button>
            <br />
            <el-button
                type="primary"
                icon="el-icon-arrow-left"
                :disabled="!rightTableDataStorage.length"
                @click="moveSelections('right', 'left')"
            ></el-button>
            <!--  <br />-->
            <!--  <el-button-->
            <!--      type="primary"-->
            <!--      icon="el-icon-d-arrow-left"-->
            <!--      :disabled="!rightTableDataStorage.length"-->
            <!--      @click="moveAllSelections('right', 'left')"-->
            <!--  ></el-button>-->
        </div>
        <!-- 右边表格数据 -->
        <div class="trant-right">
            <p>已选中</p>
            <div class="trant-content">
                <div class="content-input">
                    <el-input
                        :placeholder="rightPlaceholder || leftPlaceholder"
                        v-model="searchData.right.temp"
                        style="width:280px"
                        size="mini"
                        @keyup.enter.native="onSearch('right')"
                    ></el-input>
                    <el-button class="left-p" type="primary" icon="el-icon-search" @click="onSearch('right')"> </el-button>
                </div>
                <div>
                    <el-table
                        ref="rightTable"
                        :data="filterRightTableData"
                        tooltip-effect="dark"
                        style="width: 100%"
                        :row-key="indexKey"
                        height="300px"
                        border
                    >
                        <el-table-column type="selection" width="40" align="center" :reserve-selection="true"></el-table-column>
                        <template v-for="col in columns">
                            <el-table-column
                                v-if="!col.fun"
                                :key="col.prop"
                                :prop="col.prop"
                                :label="col.label"
                                :width="col.width"
                                show-overflow-tooltip
                            ></el-table-column>
                            <el-table-column v-if="col.fun" :key="col.prop" :label="col.label" :width="col.width" show-overflow-tooltip>
                                <template slot-scope="scope">
                                    {{ col.fun(scope.row) }}
                                </template>
                            </el-table-column>
                        </template>
                    </el-table>
                </div>
                <el-pagination
                    layout="total, prev, pager, next"
                    :total="filterRightTableAllData.length"
                    :page-size="page.right.pageSize"
                    :current-page.sync="page.right.currentPage"
                    background
                ></el-pagination>
            </div>
        </div>
    </div>
</template>
<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { getCurrentPageData } from '@/utils/tools';
import { checkTableField } from '@/pages/quota/api';
@Component({
    name: 'CalculateFactorTrantableInline',
})
export default class CalculateFactorTrantableInline extends Vue {
    @Prop({ required: true }) url!: string;
    // 主键
    @Prop() indexKey: string;
    // 右边表格数据
    @Prop() rightTableData!: any[];
    // 左边、右边表格数据格式
    @Prop() columns: any;
    // 搜索输入框提示
    @Prop({ default: '请输入' }) leftPlaceholder?: string;
    @Prop() rightPlaceholder?: string;
    // 搜索的参数
    @Prop() searchNames?: string[];
    // 表名
    @Prop({ default: '' }) tableName?: string;
    // 组件内部维护的数据
    private leftTableDataStorage: any[] = [];
    private rightTableDataStorage: any[] = [];
    // 搜索条件
    private searchData = {
        left: {
            data: '',
            temp: '',
        },
        right: {
            data: '',
            temp: '',
        },
    };
    // 分页
    private page = {
        left: {
            currentPage: 1,
            pageSize: 25,
            total: 0,
        },
        right: {
            currentPage: 1,
            pageSize: 25,
            total: 0,
        },
    };
    private loading = false;

    // 选中数据备份，检测成功才能添加到该数组
    private leftOldSelections = [];

    // 选中改变时触发
    handleLeftSelections(selection) {
        const leftNewSelections = selection;
        const leftOldSelections = this.leftOldSelections;
        if (leftNewSelections.length > leftOldSelections.length) {
            // 新增
            const leftOldSelectionKeys = leftOldSelections.map(item => item[this.indexKey]);
            // 需要清理的数据
            const clearResult = leftNewSelections.filter(item => {
                return !leftOldSelectionKeys.includes(item[this.indexKey]);
            });
            const data = {
                boundCodes: clearResult.map(item => item[this.indexKey]),
                tableName: this.tableName,
            };
            checkTableField(data).then(res => {
                if (res.length) {
                    clearResult.forEach(row => {
                        (this.$refs['leftTable'] as any).toggleRowSelection(row);
                    });
                    this.yh_message_error('[' + res.join(', ') + ']范围在此计算因子中无效');
                } else {
                    this.leftOldSelections = leftNewSelections;
                }
            });
        } else {
            // 减少
            this.leftOldSelections = leftNewSelections;
        }
    }

    /**
     * 获取左侧全部数据(不分页)
     */
    async getLeftTableAllData() {
        const data = {
            filterCodes: this.rightTableDataStorage.map(item => item[this.indexKey]),
            keyName: this.searchData.left.data,
            paging: this.page.left,
        };
        this.loading = true;
        try {
            let result = (await this.$axios.post(this.url, data)) as any;
            // const list = result.list.map(item => {
            //     const props = this.columns.map(item => item.prop);
            //     let temp = {};
            //     props.forEach(pItem => {
            //         temp[pItem] = item[pItem];
            //     });
            //     return temp;
            // });

            this.page.left.total = result.total;
            this.leftTableDataStorage = result.list;
        } catch (e) {
            this.page.left.total = 0;
            this.leftTableDataStorage = [];
        } finally {
            this.loading = false;
        }
    }
    /**
     * 过滤获取右侧全部数据(不分页)
     */
    get filterRightTableAllData() {
        let data = this.rightTableDataStorage;
        let searchName = this.searchNames;
        // 匹配搜索功能
        if (searchName && searchName.length) {
            data = data.filter(item => {
                for (let i = 0; i < searchName.length; i++) {
                    let key = searchName[i];
                    let itemStr = item[key] ? String(item[key]) : '';
                    if (itemStr.indexOf(this.searchData.right.data) > -1) {
                        return true;
                    }
                }
                return false;
            });
        }
        return data;
    }
    /**
     * 过滤获取右侧当前页数据
     */
    get filterRightTableData() {
        let data = this.rightTableDataStorage;
        let searchName = this.searchNames;
        // 匹配搜索功能
        if (searchName && searchName.length) {
            data = data.filter(item => {
                for (let i = 0; i < searchName.length; i++) {
                    let key = searchName[i];
                    let itemStr = item[key] ? String(item[key]) : '';
                    if (itemStr.indexOf(this.searchData.right.data) > -1) {
                        return true;
                    }
                }
                return false;
            });
        }
        return getCurrentPageData(data, this.page.right.currentPage, this.page.right.pageSize);
    }
    /**
     * 监听两组表格数据
     */
    @Watch('rightTableData', { immediate: true, deep: true })
    async watchRightTableData() {
        this.rightTableDataStorage = JSON.parse(JSON.stringify(this.rightTableData));
        this.initParams();
        this.getLeftTableAllData();
    }

    /**
     * 搜索功能
     */
    onSearch(type: string) {
        if (this.searchData[type].temp === this.searchData[type].data) {
            return;
        }
        this.searchData[type].data = this.searchData[type].temp;
        if (type === 'left') {
            this.getLeftTableAllData();
        }
    }
    /**
     * 移动表格选中数据
     * @param from 数据来源
     * @param to   数据最终要调价的地方
     */
    moveSelections(from, to) {
        const selections: any[] = (this.$refs[from + 'Table'] as any).selection;
        this.page.left.currentPage = 1;
        this.page.right.currentPage = 1;
        if (from === 'left') {
            this.rightTableDataStorage.push(...selections);
            // 获取左边新数据
            this.getLeftTableAllData();
        } else if (from === 'right') {
            // 右移左
            const selectionKeys = selections.map(item => item[this.indexKey]);
            // 获取右边新的数据
            this.rightTableDataStorage = this.rightTableDataStorage.filter(item => {
                return !selectionKeys.includes(item[this.indexKey]);
            });
            // 获取左边新数据
            this.getLeftTableAllData();
        }

        // 清除选中项
        (this.$refs[from + 'Table'] as any).clearSelection();
        (this.$refs[to + 'Table'] as any).clearSelection();
    }

    /**
     * 移动表格所有数据
     * @param from 数据来源
     * @param to   数据最终要调价的地方
     */
    async moveAllSelections(from, to) {
        this.page.left.currentPage = 1;
        this.page.right.currentPage = 1;
        if (from === 'right') {
            this.page.right.total = 0;
            this.rightTableDataStorage = [];
            this.getLeftTableAllData();
        } else if (from === 'left') {
            this.page.left.total = 0;
            this.leftTableDataStorage = [];
            // 获取右边所有数据
            const data = {
                filterCodes: [],
                keyName: this.searchData.left.data,
                paging: {
                    total: 0,
                    currentPage: 1,
                    pageSize: 2147483647,
                },
            };
            let result;
            try {
                result = (await this.$axios.post(this.url, data)) as any;
                // const list = result.list.map(item => {
                //     const props = this.columns.map(item => item.prop);
                //     let temp = {};
                //     props.forEach(pItem => {
                //         temp[pItem] = item[pItem];
                //     });
                //     return temp;
                // });
                // const list = result.list
            } catch (e) {
                result.total = 0;
                result.list = [];
            }
            this.rightTableDataStorage = result.list;
            this.page.right.total = result.total;
        }

        // 清除选中项
        (this.$refs[from + 'Table'] as any).clearSelection();
        (this.$refs[to + 'Table'] as any).clearSelection();
    }

    /**
     * 获取左边所有数据
     */
    getLeftAllData(): any[] {
        return this.leftTableDataStorage;
    }

    /**
     * 获取右边所有数据
     */
    getRightAllData(): any[] {
        return this.rightTableDataStorage;
    }

    /**
     * 左边翻页
     */
    changeLeftCurrentPage(val) {
        this.page.left.currentPage = val;
        this.getLeftTableAllData();
    }
    /**
     * 初始化参数
     */
    initParams() {
        // 初始化翻页数据
        this.searchData.left.data = '';
        this.searchData.left.temp = '';
        this.searchData.right.data = '';
        this.searchData.right.temp = '';

        // 初始化翻页数据
        this.page.left.currentPage = 1;
        this.page.right.currentPage = 1;

        // 清空多选框状态
        this.leftNewSelections = [];
        this.leftOldSelections = [];

        // 清除选中项
        if (this.$refs['leftTable']) {
            (this.$refs['leftTable'] as any).clearSelection();
        }
        if (this.$refs['rightTable']) {
            (this.$refs['rightTable'] as any).clearSelection();
        }
    }

    /**
     * 初始化方法
     */
    initData() {
        this.initParams();
        this.getLeftTableAllData();
    }
}
</script>
<style lang="scss" scoped>
.trant {
    width: 700px;
    margin: auto;
    position: relative;

    .trant-left,
    .trant-right {
        width: 300px;
        height: 350px;

        .trant-content {
            border: 1px solid #eee;
            width: 300px;
            height: 330px;
            margin-top: 10px;

            .content-input {
                width: 290px;
                height: 40px;
                margin-top: 10px;
                background: #fff;
                padding-top: 4px;
                padding-left: 10px;
                position: relative;

                .left-p {
                    position: absolute;
                    right: 0;
                    top: 4px;

                    .el-icon-search {
                        color: #fff;
                    }
                }

                & /deep/ .el-button {
                    padding: 6px;
                }
            }
        }
    }

    .trant-but {
        position: absolute;
        top: 150px;
        left: 324px;

        .el-button {
            margin-top: 10px;
        }
    }

    .trant-right {
        position: absolute;
        top: 0;
        right: 0;
    }
}
</style>
